use anyhow::Result;
use std::env;
use wasm_workers_rs::{
    http::{self, HeaderValue, Request, Response},
    worker, Content,
};

#[worker]
fn handler(req: Request<String>) -> Result<Response<Content>> {
    let message = env::var("MESSAGE").unwrap_or_else(|_| String::from("Missing title"));

    // Applied changes here to use the Response method. This requires changes
    // on signature and how it returns the data.
    let response = format!(
        "<!DOCTYPE html>
<head>
    <title>Wasm Workers Server</title>
    <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">
    <meta charset=\"UTF-8\">
    <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/water.css@2/out/water.css\">
    <style>
        body {{ max-width: 1000px; }}
        main {{ margin: 5rem 0; }}
        h1, p {{ text-align: center; }}
        h1 {{ margin-bottom: 2rem; }}
        pre {{ font-size: .9rem; }}
        pre > code {{ padding: 2rem; }}
        p {{ margin-top: 2rem; }}
    </style>
</head>
<body>
    <main>
        <h1>{}</h1>
        <pre><code>Replying to {}
Method: {}
User Agent: {}
Payload: {}</code></pre>
        <p>
            This page was generated by a Wasm module built from Rust and running in WebAssembly.
        </p>
    </main>
</body>",
        message,
        req.uri(),
        req.method().as_str(),
        req.headers()
            .get("user-agent")
            .unwrap_or(&HeaderValue::from_str("None").unwrap())
            .to_str()
            .unwrap(),
        req.body()
    );

    Ok(http::Response::builder()
        .status(200)
        .header("x-generated-by", "wasm-workers-server")
        .body(response.into())?)
}
